SICP 习题 1.8

Exercise 1.8.  Newton's method for cube roots is based on the fact that if y is an approximation to the cube root of x,then a better approximation is given by the value

练习题1.8.牛顿法求立方根的依据是,如果y是x的立方根的一个近似值,那么一个更好的近似值是


立方根的逼近方法

对于立方根,我们要找到 guess 的改进方法,使其逼近目标值 x 的立方根,即解方程 guess^3 = x。使用牛顿法,我们可以得到一个逼近公式:

guessnew=2guess+xguess23

这个公式的原理是:我们用当前 guess 的平方根和目标值 x 的比值,逐步逼近真实值。

Racket 实现:你可以将 improve 函数写成如下形式:

(define (improve guess x)
  (/ (+ (* 2 guess) (/ x (* guess guess))) 3))

在这个函数中:

这样就可以使用这个 improve 函数来逐步逼近 x 的立方根。


附:程序

#lang racket

(define (sqrt-iter guess x)
  (if (good-enough? guess x)
      guess
      (sqrt-iter (improve guess x)
		 x)))

(define (cbrt-iter guess x)
  (if (good-enough-cbrt? guess x)
      guess
      (cbrt-iter (improve-cbrt guess x)
		 x)))

(define (improve guess x)
  (average guess (/ x guess)))

(define (improve-cbrt guess x)
  (/ (+ (* 2 guess) (/ x (* guess guess))) 3))

(define (average x y)
  (/ (+ x y) 2))

(define (square x)
  (* x x))

(define (cube x)
  (* (* x x) x))

(define (good-enough? guess x)
  (< (abs (- (square guess) x)) 0.001))

(define (good-enough-cbrt? guess x)
  (< (abs (- (cube guess) x)) 0.001))

(define (sqrt x)
  (sqrt-iter 1.0 x))

(define (cbrt x)
  (cbrt-iter 1.0 x))

(displayln (sqrt 9))
(displayln (sqrt (+ 100 37)))
(displayln (square (sqrt 1000)))

(display "Original version:\n")
(display " (0.0000001) = ")
(display (sqrt 0.0000001))
(display "\n (10000000000) = ")
(display (sqrt 10000000000))
(display "\n")

(displayln (cbrt 27))
(displayln (cbrt 1000))
(displayln (cbrt 5))

本文作者:Maeiee

本文链接:SICP 习题 1.8

版权声明:如无特别声明,本文即为原创文章,版权归 Maeiee 所有,未经允许不得转载!


喜欢我文章的朋友请随缘打赏,鼓励我创作更多更好的作品!